import type { FileInfo as FileItem } from '#/api/openapi';

import { computed, ref } from 'vue';

import { FilePreviewService } from '#/api/services';

/**
 * 文件预览功能的组合式API
 * @param shareCode 分享码
 */
export function useFilePreview(shareCode?: string) {
  const currentFile = ref<FileItem>();
  const isPreviewVisible = ref(false);
  const previewError = ref<string>();
  const loading = ref(false);

  // 计算属性：当前文件的预览URL
  const previewUrl = computed(() => {
    if (!currentFile.value || !shareCode) return '';
    return FilePreviewService.getPreviewUrl(currentFile.value, shareCode);
  });

  // 计算属性：当前文件的流媒体URL
  const streamUrl = computed(() => {
    if (!currentFile.value || !shareCode) return '';
    return FilePreviewService.getStreamUrl(currentFile.value, shareCode);
  });

  // 计算属性：当前文件是否支持预览
  const isSupported = computed(() => {
    if (!currentFile.value) return false;
    return FilePreviewService.isPreviewSupported(currentFile.value);
  });

  // 计算属性：当前文件类型
  const fileType = computed(() => {
    if (!currentFile.value) return 'other';
    return FilePreviewService.getFileType(currentFile.value);
  });

  /**
   * 打开文件预览
   * @param file 文件信息
   */
  const openPreview = (file: FileItem) => {
    currentFile.value = file;
    isPreviewVisible.value = true;
    previewError.value = undefined;
  };

  /**
   * 关闭文件预览
   */
  const closePreview = () => {
    isPreviewVisible.value = false;
    currentFile.value = undefined;
    previewError.value = undefined;
  };

  /**
   * 获取缩略图URL
   * @param file 文件信息
   * @param width 宽度
   * @param height 高度
   */
  const getThumbnailUrl = (file: FileItem, width?: number, height?: number) => {
    if (!shareCode) return '';
    return FilePreviewService.getThumbnailUrl(file, shareCode, width, height);
  };

  /**
   * 获取文件预览信息
   * @param file 文件信息
   */
  const getPreviewInfo = async (file: FileItem) => {
    if (!shareCode || !file.md5) {
      throw new Error('缺少分享码或文件MD5');
    }

    loading.value = true;
    previewError.value = undefined;

    try {
      const result = await FilePreviewService.getFilePreview(
        shareCode,
        file.md5,
      );
      return result;
    } catch (error) {
      previewError.value =
        error instanceof Error ? error.message : '获取预览信息失败';
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 检查文件是否支持预览
   * @param file 文件信息
   */
  const checkSupport = (file: FileItem) => {
    return FilePreviewService.isPreviewSupported(file);
  };

  /**
   * 获取文件类型
   * @param file 文件信息
   */
  const getFileType = (file: FileItem) => {
    return FilePreviewService.getFileType(file);
  };

  return {
    // 状态
    currentFile,
    isPreviewVisible,
    previewError,
    loading,

    // 计算属性
    previewUrl,
    streamUrl,
    isSupported,
    fileType,

    // 方法
    openPreview,
    closePreview,
    getThumbnailUrl,
    getPreviewInfo,
    checkSupport,
    getFileType,
  };
}
